from orm_learning.advanced_orm_learning.model.permissions import Permissions
from orm_learning.advanced_orm_learning.model.users import Users

class UserService:
    def __init__(self, session):
        self.session = session

    def add_user_with_permissions(self, username, password, permission_names):
        user = Users(username=username, password=password)
        permissions = [Permissions(name=perm) for perm in permission_names]
        user.permissions.extend(permissions)
        self.session.add(user)
        self.session.commit()

    def get_users_with_permissions(self):
        return self.session.query(Users).all()

    def find_user_by_username(self, username):
        return self.session.query(Users).filter_by(username=username).first()

    def delete_user_by_username(self, username):
        user = self.find_user_by_username(username)
        if user:
            self.session.delete(user)
            self.session.commit()
            return True  # Indicate successful deletion
        return False  # Indicate user not found

    def update_user_password(self, username, new_password):
        user = self.find_user_by_username(username)
        if user:
            user.password = new_password
            self.session.commit()
            return True  # Indicate successful update
        return False  # Indicate user not found
